package com.yc.oop7;

import java.util.Arrays;

public class InterfaceDemo {
	
	// 排序
	public static void sort( int[] arr ) {
	    System.out.println("排序前:"+ Arrays.toString(arr));
		for(int i = 0; i< arr.length - 1; i++) {
			for(int j = 0; j< arr.length - i - 1; j++) {
				if(arr[j] > arr[j+1]) {
					int k = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = k;
				}
			}	
		}
		System.out.println("排序后:"+ Arrays.toString(arr));
	}
	
//	public static void sort(Student[] arr) {
//		// ...
//	}
//	
//	public static void sortByAge(Student[] arr) {
//		// ...
//	}
//	
//	public static void sortByHeight(Student[] arr) {
//		// ...
//	}
	
	public static void sort(Object[] arr, Comparetor c) {
		System.out.println(" ==== 排序前:"+ 
				Arrays.toString(arr).replaceAll("\\],", "\\],\r\n"));
		for(int i = 0; i< arr.length - 1; i++) {
			for(int j = 0; j< arr.length - i - 1; j++) {
				if(c.compare(arr[j], arr[j+1])) {
					Object k = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = k;
				}
			}	
		}
		System.out.println(" ==== 排序后:"+ 
				Arrays.toString(arr).replaceAll("\\],", "\\],\r\n"));
	}
	
	// 比较器, 只有一个方法的接口 java称为 函数接口
	static interface Comparetor{
		boolean compare(Object a, Object b);
	}
	
	
	public static void main(String[] args) {
		Object[] arr = {23,42,77,11,1,96,6,7,8};
		sort(arr, new Comparetor() {
			@Override
			public boolean compare(Object a, Object b) {
				int aa = (int) a;
				int bb = (int) b;
				return aa > bb;
			}});
		
		
		Object[] stus = new Student[10];
		for(int i=0; i<10;i++) {
			Student s = new Student();
			s.name = "张" + i;
			s.age = (int) (Math.random() * 10 + 10);
			s.height = (float) (Math.random()*0.5 + 1.3);
			s.weight = (Math.random()*50 + 50);
			stus[i] = s;
		}
		
		// 对年龄排序
		sort(stus, new Comparetor() {
			@Override
			public boolean compare(Object a, Object b) {
				Student aa = (Student) a;
				Student bb = (Student) b;
				return aa.age > bb.age;
			}});
		
		// 函数接口的匿名类, 可以简化成 lambda 表达式
		sort(stus, (a, b) -> {
			Student aa = (Student) a;
			Student bb = (Student) b;
			return aa.height < bb.height;
		});
		
		// 体重排序
		sort(stus, (a, b) -> ((Student) a).weight < ((Student) b).weight);
		
		
		Z z1 = Z.createZ();
		Z z2 = Z.createZ();
		Z z3 = Z.createZ();
		
		System.out.println(z1 == z2);
		System.out.println(z3 == z2);
		System.out.println(z1 == z3);
		
	}
	
	// 思考, 如何使用 sort 对 学生的年龄, 身高, 体重排序?

}

class Student{
	String name;
	int age;
	float height;
	double weight;
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", height=" + height + ", weight=" + weight + "]";
	}
}


final class Z {
	private static Z z = new Z();
	private Z() {}
	// 静态工厂方法
	public static Z createZ() {
		return z;
	}
	
	static int a;
	static void test() {
		//demo();
	}
	
	
	void demo() {
		System.out.println(a);
		test();
	}
	
	
}




















